<template>
  <assemble-monitor-svg :dataList="dataList" :style="svgStyle"></assemble-monitor-svg>
</template>
<script>
import AssembleMonitorSvg from '@/components/monitor-svg/assemble-monitor-svg'
import { setInterval } from 'timers';
import * as underscore from 'underscore'
export default {
  name: 'AssembleWorkshopMonitor',
  components: { AssembleMonitorSvg },
  data() {
    return {
      //test
      dataList: [],
      set: null,
      i: 0,
      svgStyle: {width: '100%', height: '100%'},
      // websocket
      websocket: null,
      websocketReconnect: false,
      baseUrl: ""
    }
  },
  mounted() {
    this.baseUrl = process.env.VUE_APP_BASE_API;
    this.initWebSocket();
    this.svgStyle.height = document.documentElement.clientHeight - 100 + 'px'
    // setInterval(() => {
    //   this.dataList = this.randomData()
    // }, 2000)
  },
  methods: {
    // test
    randomData() {
      // test
      const list = []
      for (let index = 0; index < 30; index++) {
        const element = Math.floor(Math.random() * 3);
        list.push(element)
      }
      this.i ++
      console.log(this.i)
      return list
    },
    initWebSocket() {
      //初始化weosocket
      this.websocket = new WebSocket(
        this.baseUrl.replace("http", "ws") + "/websocket/line|3000|01"
      );
      this.websocket.onopen = () => {
        console.log("Socket 已打开");
        // this.websocket.send("消息发送测试(From Client)");
      };
      this.websocket.onerror = () => {
        console.log("Socket发生了错误");
        this.reconnectWebSocket();
      };
      this.websocket.onmessage = (msg) => {
        const lineData = JSON.parse(msg.data)
        if (this.dataList.length > 0) {
          // this.dataList[this.dataList.findIndex(a => a.lineNo === lineData.lineNo)] = lineData
          // watch无法监听数组成员变化，需要特殊方法
          this.$set(this.dataList, this.dataList.findIndex(a => a.lineNo === lineData.lineNo), lineData);
        } else {
          this.dataList = JSON.parse(msg.data);
        }
      };
      this.websocket.onclose = () => {
        console.log("Socket已关闭");
      };
    },
    //重连 待测试有问题，可能启动多个websocket
    reconnectWebSocket() {
      // reconnect重连会多次触发，所以需要给重连加一把锁，当一个重连正在执行的时候，无法再触发一次重连
      if (this.websocketReconnect) return;
      this.websocketReconnect = true;
      setTimeout(() => {
        console.log(new Date().getMinutes() + ":" + new Date().getSeconds());
        this.initWebSocket();
        this.websocketReconnect = false;
      }, 2000);
    }
  },
  destroyed() {
    this.websocket.close()
  }
}
</script>